package by.jtraining.london.repo.Impl;

import javax.persistence.EntityManager;

import javax.persistence.TypedQuery;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.jtraining.london.model.User;

import by.jtraining.london.repo.UserRepository;

import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

public class UserRepositoryImpl extends GenericRepositoryImpl<User, Long>
		implements UserRepository {
	private static final Logger LOG = LoggerFactory
			.getLogger(UserRepositoryImpl.class);
	@Inject
	public UserRepositoryImpl(EntityManager entityManager) {
		super(entityManager, User.class);
	}

	@Transactional
	public User getUserByLoginAndPassword(String login, String password) {
		
		LOG.debug("Trying to find User by login= {} and password= {}",login,password);
		TypedQuery<User> query = em
				.createQuery(
						"SELECT us FROM User AS us WHERE us.login = :login AND us.passwordHash=:password",
						User.class);
		query.setParameter("login", login);
		query.setParameter("password", password);
		User user = query.getSingleResult();
		LOG.debug("Found next user: {}",user);
		return user;
	}

	@Transactional
	public User getUserByLogin(String login) {
		LOG.debug("Trying to find User by login = {}",login);
		TypedQuery<User> query = em
				.createQuery(
						"SELECT us FROM User AS us WHERE us.login = :login",
						User.class);
		query.setParameter("login", login);
		User user = query.getSingleResult();
		LOG.debug("Found next user: {}",user);
		return user;
	}

	@Transactional
	public void changePassword(String login, String pass) {
		LOG.debug("Trying to change user's password by login = {}",login);
		User user = getUserByLogin(login);
		user.setPasswordHash(pass);
		save(user);
		LOG.debug("changed user's password");
	}

}
